package domain;

import java.sql.ResultSet;
import java.util.ArrayList;


public class DAOContact {
	public static String tableName = "contacts";
	
	public static void addContact(String firstName, String secondName, String email){	
		String req = "INSERT INTO " + tableName + " (firstName, secondName, email) VALUES ('"
					+ firstName + "', '" + secondName + "', '" + email + "');";
		
		MyJDBC myJDBC = new MyJDBC();
		myJDBC.connect();
		myJDBC.sendRequest(req);
		myJDBC.disconnect();

	}
	
	public static void removeContact(int id){
		String req = "DELETE FROM " + tableName + " WHERE id=" + id + ";";
		
		MyJDBC myJDBC = new MyJDBC();
		myJDBC.connect();
		myJDBC.sendRequest(req);
		myJDBC.disconnect();		
	}
	
	public static void updateContact(int id, String firstName, String secondName, String email){
		String req = "UPDATE " + tableName + "\n"
					+ "SET firstName='" + firstName + "', secondName='" + secondName + "'"
					+ ", email='" + email + "'\n"
					+ "WHERE id=" + id + ";";
		
		MyJDBC myJDBC = new MyJDBC();
		myJDBC.connect();
		myJDBC.sendRequest(req);
		myJDBC.disconnect();
	}
	
	
	public static Contact[] searchContact(int id){
		String req = "SELECT * FROM " + tableName + " WHERE id=" + id + ";";
		
		MyJDBC myJDBC = new MyJDBC();
		myJDBC.connect();
		ResultSet res = myJDBC.sendRequest(req);
		Contact[] tab = resultSet2Tab(res);
		myJDBC.disconnect();
		return tab;
	}
	
	public static Contact[] getContacts(){
		String req = "SELECT * FROM " + tableName;
		
		MyJDBC myJDBC = new MyJDBC();
		myJDBC.connect();
		ResultSet res = myJDBC.sendRequest(req);
		Contact[] tab = resultSet2Tab(res);
		myJDBC.disconnect();
		return tab;
	}
	
	public static Contact[] resultSet2Tab(ResultSet res){
		if(res == null)
			return new Contact[0];
		
		ArrayList<Contact> contacts = new ArrayList<Contact>();
		try {
			String idStr, firstName, secondName, email;
			int id;
			while(res.next()){
				idStr = res.getString("id");
				firstName = res.getString("firstName");
				secondName = res.getString("secondName");
				email = res.getString("email");
				id = Integer.parseInt(idStr);
				
				contacts.add(new Contact(id, firstName, secondName, email));
			}
		} catch (Exception e) {
			// do nothing
		}
		Contact[] tab = new Contact[contacts.size()];
		contacts.toArray(tab);
		return tab;
	}
}
